import { useLocation } from "react-router";
import { useRouteStore } from "@/store";

const KeepAliveItem = ({ children, keepAlive, visible }) => {
  /** 非keepalive的元素, 直接卸载 */
  if (!keepAlive) return visible ? children : null;

  /** 对于keepalive元素需要保持dom的存在 */
  return (
    <div className="keep-alive" style={{ height: '100%', display: visible ? 'block' : 'none'}}>
    {children}
    </div>
  );
};

export default function KeepAliveOutlet(){
  let { cacheRoutes } = useRouteStore()
  let { pathname: activePathname } = useLocation()
  // console.log('cacheRoutes', cacheRoutes)
  // console.log('activePathname', activePathname)
  return (cacheRoutes || []).map(({ pathname, keepAlive, children }) => (
    <KeepAliveItem
      key={pathname}
      keepAlive={keepAlive}
      visible={pathname === activePathname}
    >
      {children}
    </KeepAliveItem>
  ))
}
